//
//  SHUploadFileManager.m
//  Soha
//
//  Created by 谭飞 on 2018/9/11.
//  Copyright © 2018年 LB. All rights reserved.
//

#import "SHUploadFileManager.h"

@interface SHUploadFileManager ()

@end

@implementation SHUploadFileManager

/**
 上传单张图片

 @param image 要上传的图片
 @param token 七牛上传token
 */
+ (void)uploadWithImage:(UIImage *)image token:(NSString *)token completion:(FinishedBlock)block  {
    NSData *data;
    if (UIImagePNGRepresentation(image) == nil){
        data = UIImageJPEGRepresentation(image, 0.5);
    } else {
        data = [[self alloc] compressImage:image];
    }
    
    QNUploadManager *manager = [[QNUploadManager alloc] init];
    [manager putData:data key:[self qnImageFilePathName] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.ok) {
            NSLog(@"上传图片成功: %@",resp);
        } else {
            NSLog(@"上传失败: %@",info);
        }
        if (block) {
            block(key);
        }
    } option:nil];
}



/**
 上传多张图片

 @param images 上传的图片数组
 @param token 上传token
 @param completeHandler 请求完成回调
 */
+ (void)uploadWithImages:(NSArray<UIImage *> *)images token:(NSString *)token complete:(void(^)(NSArray *imageKeys))completeHandler {
    dispatch_group_t uploadGroup = dispatch_group_create();
    NSMutableArray *imageKeys = [NSMutableArray array];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        dispatch_group_enter(uploadGroup);
        NSData *data;
        if (UIImagePNGRepresentation(obj) == nil){
            data = UIImageJPEGRepresentation(obj, 1);
        } else {
            data = [[self alloc]compressImage:obj];
        }
        [upManager putData:data key:[self qnImageFilePathName] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.ok && key !=nil) {
                NSLog(@"上传成功: %@", resp);
            } else {
                NSLog(@"上传失败: %@",info);
            }
            NSString *completeUrl = [NSString stringWithFormat:@"%@/%@", [TFUserDefault valueForKey:@"imageUrl"], key];
            [imageKeys addObject:completeUrl];
            dispatch_group_leave(uploadGroup);
        } option:nil];

    }];
    
    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(), ^{
        if (completeHandler != nil) {
            completeHandler([imageKeys copy]);
        }
    });
}


/**
 上传视频

 @param url 视频地址
 @param token 七牛上传token
 @param block 请求完成回调
 */
+ (void)uploadVideoWithUrl:(NSString *)url token:(NSString *)token completion:(FinishedBlock)block {
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil
                                                        progressHandler:^(NSString *key, float percent) {
                                                            NSLog(@"上传进度 %.2f", percent);}
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    [upManager putData:data key:[self qnVideoFilePatName] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.ok) {
            NSLog(@"上传视频成功: %@",resp);
        } else {
            NSLog(@"上传失败: %@",info);
        }
        if (block) {
            block(key);
        }
    } option:opt];
}


#pragma mark - 上传的文件名
+ (NSString *)qnImageFilePathName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *currentDateStr = [formatter stringFromDate:[NSDate date]];
    char datax[12];//十六位防重字符
    for (int x=0;x<12;datax[x++] = (char)('A' + (arc4random_uniform(26))));
    NSString *number = [[NSString alloc] initWithBytes:datax length:12 encoding:NSUTF8StringEncoding];
    //当前时间戳
    NSInteger timeInterval = (NSInteger)[[NSDate date]timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"Image\%@\%ld%@.jpg",currentDateStr,timeInterval,number];
    return fileName;
}

+ (NSString *)qnVideoFilePatName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *now = [formatter stringFromDate:[NSDate date]];
    NSString *number = [self generateTradeNO];
    //当前时间
    NSInteger timeInterval = (NSInteger)[[NSDate date]timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"Video\%@\%ld%@.mp4",now,timeInterval,number];
    return fileName;
}

+ (NSString *)generateTradeNO {
    static int kNumber = 8;
    NSString *sourceStr = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++) {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

#pragma mark - 图片压缩
- (NSData *)compressImage:(UIImage *)image {
    NSData *imageData = UIImagePNGRepresentation(image);
    if (imageData.length / 1024 <= 512) {
        return imageData;
    }
    CGFloat imagePixel = image.size.width * kMainScreenWidth * image.size.height * kMainScreenScale;
    CGFloat shouldDataSize = imagePixel * 0.5;
    CGFloat ratio = imageData.length / shouldDataSize;
    NSData *resultData = UIImageJPEGRepresentation(image, ratio);
    NSLog(@"\n图片压缩前大小：%lub, \n图片压缩后大小：%lub, \n共压缩%luKB",imageData.length, resultData.length, ((imageData.length - resultData.length)/1024) );
    return resultData;
}

@end
